package cxm.proj.sms;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

import android.util.Log;
import cxm.com.util.MyApplication;
import cxm.com.util.MyLog;
import cxm.com.util.StorageHelper;

public class Configure {
	public enum ConfigureOption { // options saved in XML files
		PhoneNumber,
		Toggle1Open,
		Toggle1Close,
		Toggle1Status,
		Toggle1Text,
		Toggle2Open,
		Toggle2Close,
		Toggle2Status,
		Toggle2Text,
		Toggle3Open,
		Toggle3Close,
		Toggle3Status,
		Toggle3Text,
		Toggle4Open,
		Toggle4Close,
		Toggle4Status,
		Toggle4Text,
		Toggle5Open,
		Toggle5Close,
		Toggle5Status,
		Toggle5Text,
		Toggle6Open,
		Toggle6Close,
		Toggle6Status,
		Toggle6Text,
		Toggle7Open,
		Toggle7Close,
		Toggle7Status,
		Toggle7Text,
		Toggle8Open,
		Toggle8Close,
		Toggle8Status,
		Toggle8Text,
		UpgradeServer
	}
	private static String [] defaultConfigues = {"",
		"Open1", "Close1", "false", "", "Open2", "Close2", "false", "",
		"Open3", "Close3", "false", "", "Open4", "Close4", "false", "",
		"Open5", "Close5", "false", "", "Open6", "Close6", "false", "",
		"Open7", "Close7", "false", "", "Open8", "Close8", "false", "",
		"www.hfmee.com" };
	
	private static Configure instance = null;
	
	DocumentBuilder builder;
	private Document dom;
	private String saveFileName = null;
	
	private Configure() {
		this.saveFileName = MyApplication.context.getPackageName() + ".xml";
		try {
	    	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	    	this.builder = factory.newDocumentBuilder();
	    	this.dom = builder.parse(new InputSource(new FileInputStream(
	    			StorageHelper.getFile(StorageHelper.StorageType.StorageExtrenal,
	    					this.saveFileName))));
    	}
    	catch (Exception e) {
    		Log.d("Configure", "Cannot open config file: " + e);
    		this.resetDefault();
    	}
	}
	
	public void setConfig(ConfigureOption option, String value) {
		try {
			Node node = this.dom.getDocumentElement().getElementsByTagName(option.toString()).item(0);
			node.setTextContent(value);
			this.saveFile();
			MyLog.Log(MyLog.Level.Debug, "Save configure " + option.toString() +
					" with value" + value);
		} catch (Exception e) {
			Log.d("Configure", "Cannot set option "+ option.toString() + " value " + value + ": " + e);
			// set default
			this.resetDefault();
		}
	}
	
	public String getDefaultConfigString(ConfigureOption option) {
		ConfigureOption optionArray[] = ConfigureOption.values();
		for (int i = 0; i < optionArray.length; i++) {
			if (optionArray[i] == option)
				return defaultConfigues[i];
		}
		
		return "";
	}
	
	public String getConfigString(ConfigureOption option) {
		try {
			Node node = this.dom.getDocumentElement().getElementsByTagName(option.toString()).item(0);
			return node.getTextContent();
		} catch (Exception e) {
			Log.d("Configure", "Cannot get config " + option.toString() + ": " + e);
			// set default
			this.resetDefault();
			// find default value to return
			ConfigureOption optionArray[] = ConfigureOption.values();
			for (int i = 0; i < optionArray.length; i++) {
				if (optionArray[i] == option)
					return defaultConfigues[i];
			}
			
			return "";
		}
	}
	
	public boolean getConfigBool(ConfigureOption option) {
		String value = this.getConfigString(option);
		if ("" == value || null == value)
			return false;
		return Boolean.valueOf(value);
	}
	
	// reset default config file
	private void resetDefault() {
		try {
			// create default dom
			this.dom = this.builder.parse(new InputSource(
					new ByteArrayInputStream("<data></data>".getBytes())));
			
			// append every default option
			Element root = this.dom.getDocumentElement();
			ConfigureOption[] optionsArray = ConfigureOption.values();
			for (int i = 0; i < optionsArray.length; i++) {
				Element valueElement = this.dom.createElement(optionsArray[i].toString());
				valueElement.setTextContent(defaultConfigues[i]);
				root.appendChild(valueElement);
			}
			
			this.saveFile();
		}
		catch (Exception e) {
			Log.d("Configure", "Cannot create default document: " + e);
		}
	}
	
	private void saveFile() {
		try {
			// save file
			Transformer t = TransformerFactory.newInstance().newTransformer();
	    	t.setOutputProperty("indent", "yes");
	    	t.transform(new DOMSource(this.dom), new StreamResult(new FileOutputStream(
	    			StorageHelper.getFile(StorageHelper.StorageType.StorageExtrenal,
	    			this.saveFileName))));
	        /*
	        File file = StorageHelper.getFile(StorageHelper.StorageType.StorageExtrenal,this.saveFileName);
	
			OutputStream outputStream = new FileOutputStream(file);
			outputStream.write(valueString.getBytes());
			outputStream.close();
			*/
		} catch (Exception e) {
			Log.d("Configure", "Cannot save file: " + e);
		}
	}
	
	public static Configure getInstance() {
		if (null == Configure.instance)
			Configure.instance = new Configure();
		return Configure.instance;
	}
}

